package com.horizon.common.context;

import lombok.AllArgsConstructor;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;

/**
 * 地平线系统上下文.
 *
 * @author zhaoshb
 * @since 2022/12/3 11:05
 */
@Component
@AllArgsConstructor
public class HorizonContext implements ApplicationContextAware {

    private static HorizonContext instance;

    private ResourceBundleMessageSource messageSource;

    private ApplicationContext applicationContext;

    @PostConstruct
    public void init() {
        messageSource.setDefaultEncoding(StandardCharsets.UTF_8.name());
        HorizonContext.instance = this;
    }

    public static HorizonContext getInstance() {
        return instance;
    }

    public static ResourceBundleMessageSource getMessageSource() {
        return instance.messageSource;
    }

    public static <T> T getBean(Class<T> type) {
        return instance.applicationContext.getBean(type);
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
